package org.crl.blogsystem.service;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.transaction.Transactional;
import org.crl.blogsystem.entity.User;
import org.crl.blogsystem.entity.UserFollow;
import org.crl.blogsystem.entity.dto.UserDTO;
import org.crl.blogsystem.repository.UserFollowRepository;
import org.crl.blogsystem.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserFollowRepository userFollowRepository;

    @Autowired
    MinioService minioService;

    @Override
    public User add(UserDTO userDTO) {
        if (userRepository.existsByPhone(userDTO.getPhone())){
            return null;
        }
        else {
            String defaultAvatar = "/avatar/icon/f9256155491e54bf5e99bf29eece0156_512_512.jpg";
            User newUser = new User();
            BeanUtils.copyProperties(userDTO, newUser);
            newUser.setAvatar(defaultAvatar);
            newUser.setCreated_at(LocalDateTime.now());
            newUser.setSignature("这个人很懒，什么都没留下");
            newUser.setUsername("用户_" + new Random().nextInt(10000));
            newUser.setFollowcount(0);
            newUser.setFollowercount(0);
            return userRepository.save(newUser);
        }
    }

    @Override
    public User update(Long id, UserDTO userDTO) {
        User existingUser = userRepository.findById(id).orElseThrow();
        if (userDTO.getUsername() != null) {
            existingUser.setUsername(userDTO.getUsername());
        }
        if (userDTO.getAvatar() != null) {
            existingUser.setAvatar(userDTO.getAvatar());
        }
        if (userDTO.getSignature() != null) {
            existingUser.setSignature(userDTO.getSignature());
        }
        if (userDTO.getPhone() != null) {
            existingUser.setPhone(userDTO.getPhone());
        }
        if (userDTO.getPassword() != null) {
            existingUser.setPassword(userDTO.getPassword());
        }
        if (userDTO.getBirth_day()!= null) {
            System.out.println("生日" + userDTO.getBirth_day());
            existingUser.setBirthday(userDTO.getBirth_day());
            System.out.println("生日" + existingUser.getBirthday());
        }
        if (userDTO.getSex() != null) {
            existingUser.setSex(userDTO.getSex());
        }
        return userRepository.save(existingUser);
    }

    @Override
    public void delete(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public Set<User> getFollowing(Long userId) {
        List<UserFollow> followingList = userFollowRepository.findByFollowerIdAndState(userId, 1);
        Set<User> following = new HashSet<>();
        for (UserFollow uf : followingList) {
            following.add(uf.getFollowing());
        }
        return following;
    }

    @Override
    public Set<User> getFollowers(Long userId) {
        List<UserFollow> follows = userFollowRepository.findByFollowingIdAndState(userId, 1);
        Set<User> followers = new HashSet<>();
        for (UserFollow uf : follows) {
            followers.add(uf.getFollower());
        }
        return followers;
    }

    @Override
    public User getById(Long userId) {
        if (userRepository.existsById(userId)) {
            return userRepository.findUsersById(userId);
        }
        return null;
    }

    @Override
    public boolean isLogin(Long loginId) {
        return StpUtil.isLogin(loginId);
    }

    @Override
    public boolean isFollowing(Long userId) {
        Long loginId = StpUtil.getLoginIdAsLong();
        return userFollowRepository.existsByFollowerIdAndFollowingIdAndState(loginId, userId, 1);
    }

    @Override
    public String uploadAvatar(MultipartFile avatarImage) {
        Long userId = StpUtil.getLoginIdAsLong();
        if (!avatarImage.isEmpty()) {
            String folder = "/avatar/" + userId + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String avatar = minioService.uploadFile(folder, avatarImage);
            if (avatar != null) {
                User user = userRepository.findUsersById(userId);
                user.setAvatar(avatar);
                userRepository.save(user);
                return avatar;
            } else {
                return "上传失败";
            }
        }
        return "";
    }

    @Override
    @Transactional
    public Integer doFollow(Long userId) {
        int result = -2;
        Long loginId = StpUtil.getLoginIdAsLong();
        if (userId.equals(loginId)) {
            System.out.println("不能关注自己");
            return 0;
        }
        boolean existsFollowing = userFollowRepository.existsByFollowerIdAndFollowingId(loginId, userId);
        User follower = userRepository.findById(loginId).orElseThrow(() -> new RuntimeException("该用户不存在"));
        User following = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("该用户不存在"));
        if (existsFollowing) {
            UserFollow userFollow = userFollowRepository.findByFollowerIdAndFollowingId(loginId, userId);
            boolean isFollowing = userFollow.getState() == 1;
            if (isFollowing) {
                userFollow.setState(0);


                follower.setFollowcount(follower.getFollowcount() - 1);
                following.setFollowercount(following.getFollowercount() - 1);
                userRepository.save(following);
                userRepository.save(follower);
                userFollowRepository.save(userFollow);
                result = -1;
            } else {
                userFollow.setState(1);
                follower.setFollowcount(follower.getFollowcount() + 1);
                following.setFollowercount(following.getFollowercount() + 1);
                userRepository.save(following);
                userRepository.save(follower);
                userFollowRepository.save(userFollow);
                result = 1;
            }
        } else {
            UserFollow userFollow = new UserFollow(follower, following);
            userFollowRepository.save(userFollow);

            follower.setFollowcount(follower.getFollowcount() + 1);
            following.setFollowercount(following.getFollowercount() + 1);

            userRepository.save(follower);
            userRepository.save(following);
            result = 1;
        }
        return result;
    }

    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("该用户不存在"));

        System.out.println("旧密码" + oldPassword);
        System.out.println("新密码" + newPassword);
        System.out.println("用户密码" + user.getPassword());
        if (!user.getPassword().equals(oldPassword)) {
            System.out.println("旧密码错误");
            return false;
        }

        System.out.println("修改密码" + newPassword);
        user.setPassword(newPassword);
        userRepository.save(user);
        return true;
    }
}
